Grokking LinkedIn Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
LinkedIn Easy
Find Pivot Index (easy)
Solution: Find Pivot Index
Isomorphic Strings (easy)
Solution: Isomorphic Strings
Second Minimum Node In a Binary Tree (easy)
Solution: Second Minimum Node In a Binary Tree
Minimum Time to Type Word Using Special Typewriter (easy)
Solution: Minimum Time to Type Word Using Special Typewriter
Intersection of Two Arrays (easy)
Solution: Intersection of Two Arrays
Can Place Flowers (easy)
Solution: Can Place Flowers
Valid Perfect Square (easy)
Solution: Valid Perfect Square
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Sqrt (easy)
Solution: Sqrt
Valid Palindrome (easy)
Solution: Valid Palindrome
Rotate List (medium)
Solution: Rotate List
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Valid Triangle Number (medium)
Solution: Valid Triangle Number
Valid Parenthesis String (medium)
Solution: Valid Parenthesis String
Edit Distance (medium)
Solution: Edit Distance
Remove All Ones With Row and Column Flips II (medium)
Solution: Remove All Ones With Row and Column Flips II
Reverse Integer (medium)
Solution: Reverse Integer
Triplet Sum to Zero (medium)
Solution: Triplet Sum to Zero
Longest Substring Without Repeating Characters (medium)
Solution: Longest Substring Without Repeating Characters (medium)
Decode Ways (medium)
Solution: Decode Ways
Quadruple Sum to Target (medium)
Solution: Quadruple Sum to Target
Next Permutation (medium)
Solution: Next Permutation
Search in Rotated Array (medium)
Solution: Search in Rotated Array
Word Search (medium)
Solution: Word Search
Remove Nth Node From End of List (Medium)
Solution: Remove Nth Node From End of List
House Robber II (medium)
Solution: House Robber II
Coin Change
Solution: Coin Change
Design Add and Search Words Data Structure (medium)
Solution: Design Add and Search Words Data Structure
Merge Intervals (medium)
Solution: Merge Intervals
Number of Islands (easy)
Solution: Number of Islands
Longest Palindromic Subsequence (medium)
Solution: Longest Palindromic Subsequence
Kth Smallest Number (medium)
Solution: Kth Smallest Number
Maximum Product Subarray (medium)
Solution: Maximum Product Subarray
Same Tree (medium)
Solution: Same Tree
Max Points on a Line (hard)
Solution: Max Points on a Line
Closest Binary Search Tree Value II (hard)
Solution: Closest Binary Search Tree Value II
Word Ladder (hard)
Solution: Word Ladder
Median of Two Sorted Arrays (hard)
Solution: Median of Two Sorted Arrays
Largest Rectangle in Histogram (hard)
Solution: Largest Rectangle in Histogram
Serialize and Deserialize Binary Tree (hard)
Solution: Serialize and Deserialize Binary Tree
Solution: Sqrt

Problem Statement

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator. For example, do not use pow(x, 0.5) in C++ or x ** 0.5 in Python.

Example 1:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.8284, and since we need to return the floor of the square root (integer), hence we returned 2.  

Example 2:

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2.

Example 3:

Input: x = 2
Output: 1
Explanation: The square root of 2 is 1.414, and since we need to return the floor of the square root (integer), hence we returned 1.  

Constraints:

  • 0 <= x <= 231 - 1
Image

Solution

We can use a Binary Search approach to calculate the square root of an integer x without using any in-built sqrt function.

For any integer x, the square root of x will lie between 0 and x/2 (inclusive) for x > 2. Therefore, we can efficiently use binary search within this range to find the integer part of the square root (i.e., the floor value). By narrowing down the potential values step-by-step, binary search allows us to determine the largest integer y such that y*y is less than or equal to x.

This approach ensures an efficient and accurate computation of the square root, especially for large values of x, due to the logarithmic nature of binary search.

Step-by-Step Algorithm

  1. Handle Base Cases: If x is less than 2, return x directly (since the square root of 0 is 0, and the square root of 1 is 1).
  2. Initialize Pointers: Set left to 2 and right to x / 2.
  3. Binary Search Loop:
    • While left is less than or equal to right:
      • Calculate mid as left + (right - left) // 2.
      • Calculate num as mid * mid.
      • If num is greater than x, move right to mid - 1.
      • If num is less than x, move left to mid + 1.
      • If num equals x, return mid.
  4. Return Result: Return right as the integer part of the square root of x.

Algorithm Walkthrough

Let's consider the input n = 8:

  1. Initialize:

    • Input x = 8.
    • Since x is not less than 2, proceed to the next step.
    • Set left = 2 and right = 4 (8 // 2).
  2. First Iteration:

    • Calculate mid = 2 + (4 - 2) // 2 = 3.
    • Calculate num = 3 * 3 = 9.
    • Since num (9) is greater than x (8), move right to mid - 1 = 2.
  3. Second Iteration:

    • Now left = 2 and right = 2.
    • Calculate mid = 2 + (2 - 2) // 2 = 2.
    • Calculate num = 2 * 2 = 4.
    • Since num (4) is less than x (8), move left to mid + 1 = 3.
  4. End Loop:

    • Now left = 3 and right = 2.
    • Since left (3) is greater than right (2), exit the loop.
  5. Return Result:

    • Return right = 2 as the integer part of the square root of x = 8.

Code

Here is the code for this algorithm:

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

  1. Binary Search Algorithm: The key part of this algorithm is the binary search, which repeatedly divides the search interval in half. The time complexity of binary search is , where is the size of the search space. In this case, the search space is initially from 2 to x/2.

  2. Search Space: The maximum size of the search space is x/2 (when ). For smaller values of x, the function immediately returns x, as it's either 0 or 1.

  3. Overall Time Complexity: Considering the binary search on a range up to x/2, the time complexity is , which simplifies to .

Space Complexity

  1. Constant Extra Space: The algorithm uses a fixed number of integer variables (left, right, pivot, num), regardless of the input size.

  2. No Recursive Calls or Dynamic Allocation: The implementation does not use recursion or allocate additional data structures that grow with the input size.

  3. Overall Space Complexity: Given the constant amount of extra space, the space complexity is , meaning it's constant.

Sqrt (easy)
Valid Palindrome (easy)
Mark as Completed

On this page

Problem Statement

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity